package cn.sightsnow.zh.controller;

import cn.sightsnow.zh.entity.EasyDlResult;
import cn.sightsnow.zh.entity.EasyResult;
import cn.sightsnow.zh.entity.Image;
import cn.sightsnow.zh.repository.EasyDlResultRepository;
import cn.sightsnow.zh.repository.ImageRepository;
import cn.sightsnow.zh.service.AccessTokenService;
import cn.sightsnow.zh.util.Base64Util;
import cn.sightsnow.zh.util.GsonUtils;
import cn.sightsnow.zh.util.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.UUID;

@Api(tags = "图片上传及分类")
@RestController
@RequestMapping("/images")
@Slf4j
public class ImageController {
    ImageRepository imageRepository;
    EasyDlResultRepository easyDlResultRepository;
    //    String accessToken = "24.b934623982d7fabf19c4d2a0bc91b252.2592000.1742573049.282335-116267198";
//    String easyDlUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/Medical_wastes2";
    @Value("${easyDL.url}")
    String easyDlUrl;
    @Value("${easyDL.key}")
    String easyDlKey;
    @Value("${easyDL.secret}")
    String easyDlSecret;
    @Value("${image.upload.path}")
    String imageUploadPath;
    @Autowired
    private AccessTokenService accessTokenService;

    ImageController(ImageRepository imageRepository, EasyDlResultRepository easyDlResultRepository) {
        this.imageRepository = imageRepository;
        this.easyDlResultRepository = easyDlResultRepository;
    }

    @ApiOperation("硬件设备上传图片及分类")
    @PostMapping("bytes")
    Map<String, Object> postImageEasydlBytes(@RequestBody byte[] imageBytes) throws Exception {
        log.info("接收到硬件设备上传的照片，大小：{} 字节", imageBytes.length);
        // 调用通用方法处理图片并获取分类结果
        return processImageAndClassify(imageBytes, "hardware_upload.jpg", "硬件设备");
    }

    @ApiOperation("Web页面上传图片以及分类")
    @PostMapping("easydl")
    Map<String, Object> postImageEasyDl(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename();
        log.info("接收到Web页面上传的图片：{}，大小：{} 字节", originalFilename, multipartFile.getSize());
        byte[] imageBytes = multipartFile.getBytes();
        // 调用通用方法处理图片并获取分类结果
        return processImageAndClassify(imageBytes, originalFilename, "Web页面");
    }
    
    /**
     * 通用图片处理和分类方法
     * @param imageBytes 图片字节数组
     * @param originalFilename 原始文件名
     * @param source 图片来源（硬件设备/Web页面）
     * @return 处理结果
     * @throws Exception 处理过程中可能出现的异常
     */
    private Map<String, Object> processImageAndClassify(byte[] imageBytes, String originalFilename, String source) throws Exception {
        log.info("开始处理来自【{}】的图片：{}，大小：{} 字节", source, originalFilename, imageBytes.length);
        String accessToken = accessTokenService.getAccessToken();
        log.info("获取到的accessToken：{}", accessToken);
        
        // 调用百度EasyDL服务进行分类
        Map<String, Object> map = new HashMap<>();
        map.put("image", Base64Util.encode(imageBytes));
        map.put("top_num", 5);
        String param = GsonUtils.toJson(map);
        log.info("调用EasyDL的URL：{}", easyDlUrl);
        String result = HttpUtil.post(easyDlUrl, accessToken, "application/json", param);
        log.info("EasyDL返回结果：{}", result);
        
        EasyDlResult easyDlResult = GsonUtils.fromJson(result, EasyDlResult.class);
        log.info("解析后的EasyDlResult对象：{}", easyDlResult);
        log.info("EasyDlResult.results内容：{}", easyDlResult.getResults());
        
        // 设置识别结果
        if (easyDlResult.getResults() != null && !easyDlResult.getResults().isEmpty()) {
            Collections.sort(easyDlResult.getResults(), new Comparator<EasyResult>() {
                @Override
                public int compare(EasyResult o1, EasyResult o2) {
                    return Integer.valueOf(o2.getScore().intValue()).compareTo(Integer.valueOf(o1.getScore().intValue()));
                }
            });
            log.info("排序后的results第一项：{}", easyDlResult.getResults().get(0));
            easyDlResult.setSort_result_name(easyDlResult.getResults().get(0).getName());
            log.info("设置的sort_result_name：{}", easyDlResult.getSort_result_name());
        } else {
            log.error("【{}】上传的图片EasyDL返回结果中results为空或null", source);
        }
        
        easyDlResult.setRecognitionTime(LocalDateTime.now());
        easyDlResult = easyDlResultRepository.save(easyDlResult);
        log.info("保存到数据库后的EasyDlResult：{}", easyDlResult);
        
        // 保存图片到指定路径
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uniqueFileName = dateStr + "_" + UUID.randomUUID().toString() + ".jpg";
        
        // 确保目录存在
        String uploadDir = System.getProperty("user.dir") + File.separator + imageUploadPath;
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        
        // 使用相对路径保存文件，但考虑跨平台兼容性
        String relativePath = imageUploadPath.replace("/", File.separator);
        if (!relativePath.endsWith(File.separator)) {
            relativePath += File.separator;
        }
        String filePath = relativePath + uniqueFileName;
        
        // 保存文件
        Path path = Paths.get(uploadDir, uniqueFileName);
        Files.write(path, imageBytes);
        log.info("来自【{}】的图片已保存到: {}", source, filePath);
        
        // 保存图片信息到数据库，并建立与识别结果的关联
        Image image = new Image();
        image.setImageId(UUID.randomUUID().toString());
        image.setOriginalFilename(originalFilename);
        image.setImagePath(filePath.replace("\\", "/")); // 统一使用正斜杠存储路径
        image.setUploadTime(now);
        image.setEasyDlResultId(easyDlResult.getEasyDlResultId());
        image.setLogId(easyDlResult.getLog_id());
        imageRepository.save(image);
        log.info("图片信息已保存到数据库，ID：{}", image.getImageId());
        
        Map<String, Object> response = new HashMap<>();
        response.put("filename", uniqueFileName);
        response.put("easyDlResult", easyDlResult);
        log.info("处理完成，返回结果：{}", response);
        return response;
    }
}